import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';
import 'package:vxima/book_playlist_entity.dart';

//创建数据库
var DB_Name = "ting.db";

addPlayDet(int _id, int page, List<ListX> list) async {
  Database database = await getDatabase();
  await database.execute(
      'CREATE TABLE IF NOT EXISTS Novel_${_id}_$page ( _index INTEGER ,_id INTEGER PRIMARY KEY, title TEXT, playlink TEXT )');
  for (int i = 0; i < list.length; i++) {
    await database.execute(
        'insert into Novel_${_id}_$page (_index,_id,title,playlink) VALUES (${50 * (page - 1) + 1 + i},"${list[i].trackId}","${list[i].title}","${list[i].playPathAacv224}")');
  }
  List<Map> sss = await database.rawQuery('SELECT * FROM Novel_${_id}_$page');
  print('ddd->' + sss.toString());
}

Future<List<Map>> getDBPlayDet(int _id, int page) async {
  Database database = await getDatabase();
  List<Map> sss = await database.rawQuery('SELECT * FROM Novel_${_id}_$page where _index < ${50*page} and _index > ${50 * (page - 1)}');
  return sss;
}

addToPlayList(int _id, String cover, String title, String customTitle,String bookdesc,String authorname) async {
  Database database = await getDatabase();
  // Insert some records in a transaction
  await database.transaction((txn) async {
    int id1 = await txn.rawInsert(
        'INSERT INTO PlayList(_id, cover, title, customTitle, num , times,t_page,bookdesc,authorname) VALUES($_id, "$cover", "$title", "$customTitle", 0 , "0:0",0,"$bookdesc","$authorname")');
    print('ddd->: $id1');
  });
}

updatePlayList(int _id,String sql) async {
  Database database = await getDatabase();
  // Insert some records in a transaction
  await database.transaction((txn) async {
    int id1 = await txn.rawInsert(
        'update  PlayList set $sql  where _id = $_id ');
    print('ddd->: $id1');
  });
}

Future<List<Map>> getDbPlayList() async {
  // open the database
  Database database = await getDatabase();
  List<Map> list = await database.rawQuery('SELECT * FROM PlayList');
  return list;
}

Future<Database> getDatabase() async {
  var databasesPath = await getDatabasesPath();
  var path = join(databasesPath, DB_Name);
  // Delete the database
  // await deleteDatabase(path);
  Database database = await openDatabase(path, version: 1,
      onCreate: (Database db, int version) async {
    await db.execute(
        'CREATE TABLE IF NOT EXISTS PlayList( _id INTEGER PRIMARY KEY, cover TEXT, title TEXT, customTitle TEXT, num INTEGER, times TEXT ,t_page INTEGER,bookdesc TEXT, authorname TEXT)');
  });
  return database;
}
